from tortoise.expressions import Q, F

from app.core.crud import CRUDBase
from app.models.exams import UserAnswer, Exam
from app.schemas.exams import UserAnswerCreate, UserAnswerUpdate


class UserAnswerController(CRUDBase[UserAnswer, UserAnswerCreate, UserAnswerUpdate]):
    def __init__(self):
        super().__init__(model=UserAnswer)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs = await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict(exclude_fields=["updated_at", "deleted_at"]) for obj in objs]
        return total, data

    async def do_create(self, obj_in: UserAnswerCreate):
        ret = await self.create(obj_in=obj_in)
        if ret:
            return True
        else:
            return False

    async def do_update(self, obj_in: UserAnswerUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def do_delete(self, data_id: int):
        await self.remove(id=data_id)
        return True


user_answer_controller = UserAnswerController()
